import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './core/store'
import ElementUI from 'element-ui'
import VueClipboard from 'vue-clipboard2'
import components from './components'
import directives from './core/directives'
import filters from './core/filters'
import plugins from './core/plugins'
import constants from './core/plugins/consts'
import './assets/style/theme.scss'
import './assets/style/style.scss'
import { mapState, mapMutations } from 'vuex'
import { fetchUserMenus } from '@/api/system'

Vue.config.productionTip = false
Vue.use(ElementUI, {
  size: 'small'
})
Vue.use(VueClipboard)
Vue.use(components)
Vue.use(directives)
Vue.use(filters)
Vue.use(plugins)

new Vue({
  data: {
    loading: false
  },
  router,
  store,
  computed: {
    ...mapState(['userInfo', 'homePage'])
  },
  watch: {
    async userInfo () {
      if (this.userInfo == null) {
        return
      }
      await this.initRoutes()
    }
  },
  methods: {
    ...mapMutations(['switchCollapseMenu', 'setHomePage']),
    /**
     * 初始化本地配置
     */
    initLocalConfig () {
      // 菜单状态配置
      const menuStatus = window.localStorage.getItem('MENU_STATUS')
      if (menuStatus != null) {
        this.switchCollapseMenu(menuStatus === 'true')
      }
    },
    /**
     * 初始化路由
     *
     * @returns {Promise<void>}
     */
    async initRoutes () {
      if (this.loading || this.userInfo == null) {
        return
      }
      this.loading = true
      // 重置菜单
      this.$store.commit('resetMenus')
      // 获取菜单
      const storeMenus = this.$store.state.menuData.list
      await fetchUserMenus()
        .then(menus => {
          // 没有菜单，跳转到无权访问提示页
          if (menus.length === 0) {
            this.$router.push({
              name: 'error',
              params: {
                type: 'not-allowed'
              }
            })
            return
          }
          // 设置首页
          const homePage = this.__getHomePage(menus)
          // - 没有找到合适的首页（非外部链接、IFrame嵌入的菜单），则跳转到无权访问提示页
          if (homePage == null) {
            this.$router.push({
              name: 'error',
              params: {
                type: 'not-allowed'
              }
            })
            return
          }
          this.setHomePage(this.__getHomePage(menus))
          // 添加菜单
          storeMenus.push.apply(storeMenus, menus)
          // 添加路由
          this.__addRouters(storeMenus)
          // 404
          router.addRoute({
            path: '*',
            redirect: '/error/not-found'
          })
          // 首页
          router.addRoute({
            name: 'index',
            path: '/',
            redirect: this.homePage.uri
          })
          // 路由加载完成后，如果访问的是/，跳转至动态识别的首页
          if (this.$route.path === '/') {
            this.$router.push(this.homePage.uri)
          }
        })
        .catch(e => {
          throw e
        })
        .finally(() => {
          this.loading = false
        })
    },
    /**
     * 新建路由
     *
     * @param routes 需添加的路由
     * @param parents 需添加到的目标列表
     * @private
     */
    __addRouters (routes, parents = []) {
      if (routes == null || routes.length === 0) {
        return
      }
      const rs = router.getRoutes()
      for (const route of routes) {
        const parentsDump = JSON.parse(JSON.stringify(parents))
        parentsDump.push(route)
        if (route.type === 'DIR') {
          this.__addRouters(route.children, parentsDump)
          continue
        }
        // 外链和嵌入链，不添加路由
        if (route.type === 'EXTERNAL' || route.type === 'IFRAME') {
          continue
        }
        if (rs.findIndex(r => r.path === route.path) > -1) {
          this.__addRouters(route.children, parentsDump)
          continue
        }
        if (this.homePage == null) {
          this.setHomePage(route)
        }
        router.addRoute('layout', {
          path: route.uri,
          name: route.name,
          meta: {
            title: route.name,
            paths: [...parents.map(p => p.name), route.name]
          },
          component: () => import('@/views' + route.uri)
        })
        this.__addRouters(route.children, parentsDump)
      }
    },
    /**
     * 获取首页
     * @private
     */
    __getHomePage (menus) {
      for (const menu of menus) {
        // 目录，继续查找子菜单
        if (menu.type === constants.SYSTEM_MENU.TYPE_DIR) {
          const homePage = this.__getHomePage(menu.children)
          // 在当前目录下未找到合适的菜单作为首页，则继续查找下一级菜单
          if (homePage == null) {
            continue
          }
          return homePage
        }
        // 外部链接，不能作为首页
        if (menu.type === constants.SYSTEM_MENU.TYPE_EXTERNAL) {
          continue
        }
        // IFrame嵌套，不能作为首页
        if (menu.type === constants.SYSTEM_MENU.TYPE_IFRAME) {
          continue
        }
        return menu
      }
      return null
    }
  },
  async created () {
    if (this.userInfo == null) {
      return
    }
    await this.initRoutes()
      .catch(() => {})
  },
  mounted () {
    this.initLocalConfig()
  },
  render: h => h(App)
}).$mount('#app')
